/**
 * UserBo.java   2017年4月9日 上午11:47:54 by xuebing
 * <p>
 * Copyright (c) 2010 - 2017 All rights reserved.
 */
package com.rongmai.web.bo;

import com.rongmai.db.dto.LabelDto;
import com.rongmai.db.dto.UserAndCompanyDTO;
import com.rongmai.db.enums.CompanyStatusEnum;
import com.rongmai.db.enums.UserRoleEnum;
import com.rongmai.db.mapper.*;
import com.rongmai.db.model.*;
import com.rongmai.db.vo.Page;
import com.rongmai.db.vo.UserVo;
import com.rongmai.web.dto.MessageDTO;
import com.rongmai.web.utils.UserUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class UserBo {

    private static Logger logger = LoggerFactory.getLogger(UserBo.class);

    @Resource
    private UserMapper userMapper;
    @Resource
    private UserLoginMapper userLoginMapper;
    @Resource
    private LabelBo labelBo;
    @Resource
    private UserBo userBo;
    @Resource
    private CompanyMapper companyMapper;
    @Resource
    private CompanyAuditMapper companyAuditMapper;
    @Resource
    private DepartmentAuditMapper departmentAuditMapper;
    @Resource
    private DepartmentMapper departmentMapper;
    @Resource
    private FinanceProductAuditMapper financeProductAuditMapper;
    @Resource
    private CompanyRoleBo companyRoleBo;
    @Resource
    private UserBusinessBo userBusinessBo;

    public void create(User user) {
        user.setCreateTime(new Date());
        userMapper.insert(user);
    }

    public User createByMobile(String mobile) {
        User user = new User();
        user.setMobile(mobile);
        create(user);
        return user;
    }

    public List<UserVo> getByMobile(String mobile) {
        List<UserVo> userVos = new ArrayList<>();
        List<User> list = userMapper.getByMobile(mobile);
        for (User user : list) {
            userVos.add(convertToVo(user));
        }
        return userVos;
    }

    public UserVo getUniqueUser(String mobile, String role) {
        User user = userMapper.getByMobileAndRole(mobile, role);
        if (user == null) return null;
        return convertToVo(user);
    }

    public User getByMobileAndRole(String mobile, String role) {
        return userMapper.getByMobileAndRole(mobile, role);
    }

    public void updateUser(User user) {
        List<User> list = userMapper.getByMobile(user.getMobile());
        for (User item : list) {
            if (StringUtils.isEmpty(item.getRole()) || user.getRole().equals(item.getRole())) {
                user.setId(item.getId());
                userMapper.update(user);
                return;
            }
        }
        create(user);
    }

    public MessageDTO login(String mobile, HttpServletRequest request) {
        List<UserVo> users = getByMobile(mobile);
        User user;
        if (CollectionUtils.isEmpty(users)) {
            user = this.createByMobile(mobile);
        } else {
            UserVo userVo = users.get(0);
            user = new User();
            BeanUtils.copyProperties(userVo, user);
        }

        return setLoginMessageDTO(request, user);
    }

    private MessageDTO setLoginMessageDTO(HttpServletRequest request, User user) {
        UserUtils.setCurrentUser(request, user);

        String mobile = user.getMobile();
        UserLogin userLogin = new UserLogin();
        userLogin.setUserId(user.getId());
        userLogin.setMobile(mobile);
        String sessionId = UUID.randomUUID().toString().replaceAll("-", "");
        userLogin.setSessionId(sessionId);
        userLogin.setCreateTime(new Date());
        userLogin.setRole(user.getRole());
        userLoginMapper.insert(userLogin);

        UserLogin latestUserLogin = userLoginMapper.getLatestUserLogin(mobile);

        MessageDTO dto = new MessageDTO();
        dto.setMobile(mobile);
        dto.setSessionId(sessionId);
        dto.setLastRole(latestUserLogin == null ? "" : latestUserLogin.getRole());
        return dto;
    }

    public MessageDTO changeRole(HttpServletRequest request, User currentUser) {

        String mobile = currentUser.getMobile();
        String role = currentUser.getRole();
        User user;
        if (UserRoleEnum.FINANCE.name().equals(role)) {
            user = userBo.getUniqueUser(mobile, UserRoleEnum.INVEST.name());
        } else {
            user = userBo.getUniqueUser(mobile, UserRoleEnum.FINANCE.name());
        }
        return setLoginMessageDTO(request, user);
    }

    public User getBySessionId(String sessionId) {
        if (StringUtils.isEmpty(sessionId)) {
            return null;
        }
        UserLogin userLogin = userLoginMapper.getBySessionId(sessionId);
        if (userLogin == null) {
            return null;
        }
        return userMapper.getById(userLogin.getUserId());
    }

    public Page<UserVo> pageUser(UserVo userVo) {
        if (userVo.getPageNo() != 0) {
            userVo.setPageNo(userVo.getPageNo() - 1);
        }
        if (userVo.getPageSize() == 0) {
            userVo.setPageSize(10);
        }
        List<User> users = userMapper.pageUser(userVo);
        List<UserVo> userVos = new ArrayList<>();
        for (User user : users) {
            userVos.add(convertToVo(user));
        }
        Page<UserVo> result = new Page<>();
        result.setList(userVos);
        result.setTotal(userMapper.countUser(userVo));
        return result;
    }

    public List<UserVo> myDepartmentUser(Integer departmentId) {
        UserVo userVo = new UserVo();
        userVo.setDepartment(String.valueOf(departmentId));
        return queryUser(userVo);
    }

    public List<UserVo> queryUser(UserVo userVo) {
        List<User> users = userMapper.queryUser(userVo);
        List<UserVo> userVos = new ArrayList<>();
        for (User user : users) {
            userVos.add(convertToVo(user));
        }
        return userVos;
    }


    public List<UserVo> myCompanyUser(Integer companyId) {
        UserVo userVo = new UserVo();
        userVo.setCompanyId(companyId);
        return queryUser(userVo);
    }

    public UserVo detail(Integer id) {
        User user = userMapper.getById(id);
        return convertToVo(user);
    }

    private UserVo convertToVo(User user) {
        if (user == null) return null;
        UserVo userVo = new UserVo(user);
        userVo.setCityList(labelBo.getNameListByIds(user.getCity()));
        userVo.setIndustryList(labelBo.getNameListByIds(user.getIndustry()));
        userVo.setModelList(labelBo.getNameListByIds(user.getModel()));
        userVo.setProductList(labelBo.getNameListByIds(user.getProduct()));
        userVo.setTitleList(labelBo.getNameListByIds(user.getTitle()));
        userVo.setDepartmentList(labelBo.getNameListByIds(user.getDepartment()));
        userVo.setUserBusinesses(userBusinessBo.queryByUserId(user.getId()));
        return userVo;
    }

    public void updateCompanyAndUser(UserAndCompanyDTO userAndCompanyDTO) {
        Integer companyId;
        boolean isManager = false;
        Company companyTemp = companyMapper.getByName(userAndCompanyDTO.getCompanyName(), userAndCompanyDTO.getRole());
        if (companyTemp == null) {
            Company company = new Company();
            company.setName(userAndCompanyDTO.getCompanyName());
            company.setOrgType(userAndCompanyDTO.getOrgType());
            company.setCity(userAndCompanyDTO.getCity());
            company.setIndustryLabelIds(userAndCompanyDTO.getIndustry());
            company.setModelLabelIds(userAndCompanyDTO.getModel());
            company.setProductLabelIds(userAndCompanyDTO.getProduct());
            company.setBusiCard(userAndCompanyDTO.getBusiCard());
            company.setStatus(CompanyStatusEnum.INIT.name());
            company.setRole(userAndCompanyDTO.getRole());
            companyMapper.insert(company);
            companyId = company.getId();
            isManager = true;
        } else {
            companyTemp.setOrgType(userAndCompanyDTO.getOrgType());
            companyTemp.setCity(userAndCompanyDTO.getCity());
            companyTemp.setIndustryLabelIds(removeRepeat(companyTemp.getIndustryLabelIds(), userAndCompanyDTO.getIndustry()));
            companyTemp.setModelLabelIds(removeRepeat(companyTemp.getModelLabelIds(), userAndCompanyDTO.getModel()));
            companyTemp.setProductLabelIds(removeRepeat(companyTemp.getProductLabelIds(), userAndCompanyDTO.getProduct()));
            companyTemp.setBusiCard(userAndCompanyDTO.getBusiCard());
            companyTemp.setStatus(CompanyStatusEnum.INIT.name());
            companyMapper.update(companyTemp);
            companyId = companyTemp.getId();
        }

        Department department = departmentMapper.queryByCompanyIdAndLabelId(companyId, userAndCompanyDTO.getDepartmentLabelId());
        LabelDto labelDto = labelBo.get(userAndCompanyDTO.getDepartmentLabelId());
        if (department == null) {
            department = new Department();
            department.setCompanyId(companyId);
            department.setLabelId(userAndCompanyDTO.getDepartmentLabelId());
            department.setName(labelDto == null?"": labelDto.getName());
            departmentMapper.insert(department);
        }

        User user = new User();
        BeanUtils.copyProperties(userAndCompanyDTO, user);
        user.setDepartment(String.valueOf(userAndCompanyDTO.getDepartmentLabelId()));
        user.setCompanyId(companyId);
        user.setManager(isManager);
        updateUser(user);

//        CompanyRole companyRole= companyRoleBo.query(companyId, userAndCompanyDTO.getRole());
//        if (companyRole == null) {
//            companyRole = new CompanyRole();
//            companyRole.setCompanyId(companyId);
//            companyRole.setRole(userAndCompanyDTO.getRole());
//            companyRole.setManager(currentUser.getId());
//            companyRoleBo.save(companyRole);
//        }

        if (!CollectionUtils.isEmpty(userAndCompanyDTO.getUserBusinesses())) {
            userBusinessBo.deleteByUserId(user.getId());
            for (UserBusiness userBusiness : userAndCompanyDTO.getUserBusinesses()) {
                userBusiness.setUserId(user.getId());
                userBusinessBo.save(userBusiness);
            }
        }
    }

    private String removeRepeat(String industryLabelIds, String industry) {
        try {
            if (StringUtils.isEmpty(industryLabelIds)) {
                return industry;
            }
            if (StringUtils.isEmpty(industry)) {
                return industryLabelIds;
            }
            String[] split = industryLabelIds.split(",");
            String[] split2 = industry.split(",");
            Set<String> collect = Arrays.stream(split).collect(Collectors.toSet());
            Set<String> collect2 = Arrays.stream(split2).collect(Collectors.toSet());
            collect.addAll(collect2);
            return String.join(",", collect);
        } catch (Exception e) {
            logger.error("去重异常", e);
        }
        return null;
    }


}
